#include <stdlib.h>
#include <stdio.h>
#include <nds.h>

// common headers
#include "common.h"

// local headers
#include "library.h"

#include "languages.h"

// i18n = internationalisation

int i18n_initLang(sI18nLang *l, sFile *ld, char *ln) {
    sLibResult libres;

    if(!l || l->fd || l->lp || l->confd || !ld  || !ln) return 1;

    libres=getLibraryByFileType_cfs(ld, ln, tCONFIG);

	l->lp=newLibInstance(libres.lib);
	if(!l->lp) {
		iprintf("Can't open config library !\n");
		return 1;
	}

	l->ci=(sCInterface *)l->lp->query(QUERY_FSTRUCT);
	if(!l->ci) {
		iprintf("Can't get config library interface !\n");
		deleteLibInstance(l->lp); l->lp=NULL;
		return 1;
	}

	l->fd=fopen(libres.file->name, "rb");
	if(!l->fd) {
		iprintf("Can't open language file\n");
		deleteLibInstance(l->lp); l->lp=NULL;
		return 1;
	}

	l->confd=l->ci->open(l->fd, libres.extid);
	if(!l->confd) {
		iprintf("Can't load language file\n");
		fclose(l->fd); l->fd=NULL;
		deleteLibInstance(l->lp); l->lp=NULL;
		return 1;
	}

    return 0;
}

char *i18n_get(sI18nLang *l, char *section, u32 id) {
    if(!l || !l->ci || !l->confd) return NULL;

    char param[64];
    strcpy(param, "TEXT");
    itoa(id, param+4, 10);

    char *t=NULL;
	if(l->ci->get_string(l->confd, section, param, &t)) return NULL;

    return t;
}

void i18n_deinitLang(sI18nLang *l) {
    if(!l) return;

    if(l->confd && l->ci) l->ci->close(l->confd);
    l->confd=NULL;

    if(l->fd) fclose(l->fd);
    l->fd=NULL;

    if(l->lp) deleteLibInstance(l->lp);
    l->ci=NULL;
    l->lp=NULL;
}

